
/* CMS generic js
 *
 * Dependency: tvb-utils.js
 *             jquery-1.3.2.js
 *             jquery-laughing.js
**/

TVB.util.namespace('TVB.Cms.Components');

TVB.Cms.Components = {

    header: function (scope) {
        var alignWidth = function () {
            $(".cms-header>ul>li", scope).each(function () {
                var w1, w2;
                w1 = $(this).width();
                w2 = $(this).children('ul').width();
                if (w2 < w1) {
                    $(this).children('ul').width(w1 - 2);    //align the width of submenu with header
                }
            });
        };
        $(".cms-header li", scope).hover(function () {
            TVB.util.once(alignWidth);    //init on the fly.
            $(this).addClass('ui-state-hover');
        }, function () {
            $(this).removeClass('ui-state-hover');
        });
    },

    laughing: function (scope) {
        $(scope).find(".input_status:not([readonly])").input_status();
        $(scope).find(".ruler:not([readonly])").ruler();
    },

    textarea: function (scope) {
        $(scope).find("textarea:not([readonly])").one('focus', function () {
            $(this).text_status().focus();
        }).each(function () {    //auto expand all textarea
            var that = this;
            setTimeout(function () {
                $(that).height(80);
                var h1 = that.offsetHeight,
                    h2 = that.scrollHeight;
                if (h1 < h2) {
                    $(that).height(h2);
                }
            }, 200);
        });
    },

    datepicker: function (scope) {
        $.datepicker._doKeyUp = function(event) {
    		var inst = $.datepicker._getInst(event.target);
    		if (inst.input.val() != inst.lastVal) {
    			try {
    				var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
    					(inst.input ? inst.input.val() : null),
    					$.datepicker._getFormatConfig(inst));
    				if (date) { // only if valid
    					$.datepicker._setDateFromField(inst);
    					$.datepicker._updateAlternate(inst);
    					//$.datepicker._updateDatepicker(inst);    //commented by simon to handle the conflict with the "mask" plugin
    				}
    			}
    			catch (event) {
    				$.datepicker.log(event);
    			}
    		}
    		return true;
    	};
    	
        var timer;
        //reset the position of DatePicker 
        $.datepicker._checkOffset = function(inst,offset,isFixed){return offset;};

        $(scope).find(".datepicker:not([readonly])").datepicker({
            dateFormat: 'yy-mm-dd'
        }).one("focus", function () {
            $(this).unmask().mask("9999-19-39");
        }).blur(function (e) {
            var pattern = /^[\d]{4}\-\d{2}\-\d{2}$/,
                value = this.value,
                that = this;
            if (value !== '' && value !== '____-__-__' && !pattern.test(value)) {
                //alert(TVB.Pdes.Config.TXT.INVALID_DATE_FORMAT);
                clearTimeout(timer);
                timer = setTimeout(function () {
                    that.focus();
                }, 500);
            }
        });

        $('#ui-datepicker-div').click(function () {
            clearTimeout(timer);
        });
    },

    time: function (scope) {
        $(scope).find(".time:not([readonly])").time_widget([
            [ ['60', '+1 hour'], ['15', '+15 minutes'] ],
            [ ['-15', '-15 minutes'], ['-60', '-1 hour'] ]
        ]).keydown(
            function (event) {
                if(13 == event.keyCode){                
                    return false;
                } 
            }
        ).one("focus", function () {
            $(this).mask("29:59");
        });
        $('div.timeHhMmSs input', scope).each(function (i) {
            $(this).mask('99');
        });
    },

    button: function (scope) {
        $('input.cms-back', scope).click(function () {
            history.back();
        });
        $("input[type=button], input[type=submit], .btn", scope).hover(function () {
            $(this).addClass('ui-state-hover');
        }, function () {
            $(this).removeClass('ui-state-hover');
        });
    }

};

/*
**  country list
*/
TVB.Cms.Components.countryList = function(scope){
	var scope = $('div.cms-countrylist-item', scope), scopeDialog;
	if(!scope.length){
		return false;
	}
	var countryData = {
		handle: null,
		init: function(scope){
			this.handle = $('input.vcountry', scope);
		},
		set: function(data){
			this.handle.val( JSON.stringify(data) );
            this.handle.trigger('change');
		},
		get: function(){
			return eval('('+ this.handle.val() +')');
		}
	};
	
	var refreshCountryList = function(scope){
		countryData.init(scope);
		var i,j,k,item, dla,listEl = $('.grid-r .list', scope), data = countryData.get();
		listEl.html('');
		for(i in data){
			if(data[i] == 'ALL'){
				dla = $('<p class="a"><b>'+i+'</b> - <span class="b"><em>ALL</em></span></p>');
				listEl.append(dla);
			}else{
				for(j in data[i]){
					dla = $('<p class="a"><b>'+i+'</b> - <span class="b"></span></p>');
					var item = data[i][j], dlb;
					if(item == 'ALL'){
						//dlb = $('<dl class="c"><dt>'+j+'</dt><dd class="d"><p>ALL</p></dd></dl>');
					}else{
						var ps = [];
						for(k in item){
							ps.push('<em>'+item[k]+' ('+k+')</em>');
						}
						dlb = $(ps.join('<ins>,</ins>'));
					}
					$('.b', dla).append(dlb);
					listEl.append(dla);
				}
			}
		}
		$('dl', listEl).addClass('ui-helper-clearfix');
		$('dd', listEl).addClass('ui-helper-clearfix');
		$('em', listEl).append('<span class="ui-icon ui-icon-close"></span>');
	};
	for(var i=0,ilen=scope.length; i<ilen; i++){
		refreshCountryList(scope[i]);
	}
	var matchCountryOnSub = function(index){
		var uitab = getUiTab( scopeDialog );
		var mslis = $('.subtabs ul li', scopeDialog), msli=mslis.eq(index);
		if(msli.length != 1){
			msli = mslis.eq(0);
			index = 0;
		}
		var txt = msli.text().toLowerCase(),
			re = new RegExp('(['+txt+']{1})', 'i');
		mslis.removeClass('ui-tabs-selected ui-state-active');
		msli.addClass(' ui-tabs-selected ui-state-active');
		$('div', uitab).css('display', 'none');
		$('div.'+txt, uitab).css('display', '');
	};
	
	var initCountrySubTabs = function(){
		var i=0;
		$('.subtabs li', scopeDialog).hover(function(e){
			$(this).addClass('ui-state-hover');
		}, function(e){
			$(this).removeClass('ui-state-hover');
		}).each(function(){
			$(this).attr('index', i);
			i++;
		});
		
		$('.subtabs li', scopeDialog).bind('click', function(e){
			e.preventDefault();
			var t=e.target.nodeName == 'A' ? $(e.target).parents('li').eq(0) : $(e.target), 
				i=0, index=0,
				uitab = getUiTab( scopeDialog );
			$('.subtabs ul li', scopeDialog).each(function(){
				if(t[0] == this){
					index = i;
				}
				i++;
			});
			matchCountryOnSub(index);
			uitab.attr('sindex', index);
		});
	};
	
	var initCountryTabs = function(){
		
		scopeDialog.tabs({
			cache: true,
			selected: $('.tabs',scopeDialog).attr('selectIndex'),
			ajaxOptions: {
				success: function(r, s){
					countryData.init(scope);
					if(s == 'success'){
						var sdatas={}, data = eval('('+r+')'), oData = countryData.get(), 
							uitabs = getUiTab( scopeDialog ), sublist = $(".subtabs li", scopeDialog),
							mregin='';
						uitabs.addClass('list');
						uitabs.html('');
						for(var i in data){
							mregin= i;
							for(var j in data[i]){
								var mname = data[i][j][0]+' ('+j+')';
								for(var si=0, slen=sublist.length; si<slen; si++){
									var txt = sublist.eq(si).text().toLowerCase(),
										re = new RegExp('(['+txt+']{1})', 'i'),
										matches = data[i][j][0].substr(0,1).match(re);
									if(!sdatas[txt]){
										sdatas[txt] = []
									}
									if(matches && matches[1]){
										sdatas[txt].push([j, data[i][j][0], data[i][j][1]]);
										//break;
									}
								}
							}
						}
						for(var i in sdatas){
							var div=$('<div class="sub '+i+'"></div>'),
								dl = $('<dl><dt>'+mregin+'</dt><dd></dd></dl>'), dd=$('dd', dl);
							div.append(dl);
							div.append('<dl class="end"><dt>&nbsp;</dt><dd><p><label><input type="checkbox" class="all" />&nbsp;ALL</label></p></dd></dl>');
							
							for(var j in sdatas[i]){
								var mname = sdatas[i][j][1]+' ('+sdatas[i][j][0]+')',
									mchecked = false;
								if( oData[mregin] ){
									if(oData[mregin][mregin] && oData[mregin][mregin][sdatas[i][j][0]]){
										mchecked = true;
									}
									if(oData[mregin] == 'ALL'){
										mchecked = true;
										$('dl input.all', div).attr('checked', 'checked');
										$('input[disabled]', div).removeAttr('checked');
									}
								}
								mname = sdatas[i][j][2] ? '<s>'+mname+'</s>' : mname;
								var p = $('<p><label><input type="checkbox" value="'+sdatas[i][j][0]+'" name="'+sdatas[i][j][0]+'" label="'+sdatas[i][j][1]+'" '+(sdatas[i][j][2] ? 'disabled' : '')+' '+(mchecked ? 'checked': '')+' /> '+mname+'</label></p>');
								dd.append(p);
							}
							uitabs.append(div);
						}
						uitabs.attr('sindex', 0);
						matchCountryOnSub(0);
					}
				},
				error: function(xhr, status, index, anchor) {
					$(anchor.hash).html("Couldn't load this tab. We'll try to fix this as soon as possible. If this wouldn't be a demo.");
				}
			},
			show: function(a,b){
				var uitab=getUiTab( scopeDialog ), sindex= uitab.attr('sindex');
				matchCountryOnSub( sindex );
			}
		});
		$(".ui-tabs-nav", scopeDialog).switchClass('ui-corner-all', 'ui-corner-top');
		//$(".cms-countrylist-pop .subtabs").css('width', $(".cms-countrylist-pop").width() - 80);
		scopeDialog.bind('click', function(e){
			var t = $(e.target);
			if(t.hasClass('all')){
				var sindex=$(".subtabs li.ui-tabs-selected", scopeDialog).attr('index'), 
					uitabs = getUiTab( scopeDialog ),
					subdiv = t.parents('div.sub').eq(0);
				
				if(t[0].checked){
					$('input', subdiv).attr('checked', 'checcked');
					$('input[disabled]', subdiv).removeAttr('checked');
				}else{
					$('input', subdiv).removeAttr('checked');
				}
			}else if(e.target.nodeName == 'INPUT' && $(e.target).attr('type') == 'checkbox'){
				if(e.target.checked == false){
					t.parents('div.sub').find('input.all').removeAttr('checked');
				}
			}else if(t.hasClass('first-btn')){
				submitTabsForm(e);
			}
		});
	};
	var setCountryDataByDel = function(scope){
		if(!scope){return true}
		countryData.init(scope);
		scopeDialog = $('#'+ scope.attr('dialog'));
	
		var datas = {}, oData = countryData.get(), tabs=$('.list .a', scope);
		for(var i=0, ilen=tabs.length; i<ilen; i++){
			var k = $('b', tabs.eq(i)).text(), mlis = $('em', tabs.eq(i));
			datas[k] = datas[k] || {};
			if(mlis.eq(0).text() == 'ALL'){
				datas[k] = 'ALL';
			}else{
				datas[k][k] = datas[k][k] || {};
				for(var j=0,jlen=mlis.length; j<jlen; j++){
					var matches = mlis.eq(j).text().match(/([^\(]+)\(([^\)]+)\)/i);
					if(matches && matches[1]){
						datas[k][k][matches[2]] = matches[1];
					}
				}
			}
		}
		countryData.set(datas);
	};
	var setCountryData = function(scope){
		if(!scope){return true}
		countryData.init(scope);
		scopeDialog = $('#'+ scope.attr('dialog'));
		
		var datas = {}, oData = countryData.get(), tabs=$('.tabs li', scopeDialog);
		for(var i=0, ilen=tabs.length; i<ilen; i++){
			var item=null,isv=false, item2={}, item2len=0,tab = tabs.eq(i), uitab = $('.ui-tabs-panel', scopeDialog).eq(i), dls = $('dl', uitab),selectall=1;
			if(!uitab.hasClass('list')){
				if(oData[tab.text()]){
					datas[tab.text()] = oData[tab.text()];
				}
				continue;
			}
			$('input.all', uitab).each(function(){
				if( !this.checked){ selectall=0;}
			});
			if(selectall && $('input.all', uitab).length){
				item = 'ALL';
				isv=true;
			}else{
				item = {};
				for(var j=0,jlen=dls.length; j<jlen; j++){
					if(!$(dls[j]).hasClass('end')){
						var key2 = $('dt', dls[j]).text(), vals = $('dd input', dls[j]);
						for(var ii=0, iilen=vals.length; ii<iilen; ii++){
							if(vals[ii].checked){
								item2len++;
								var mkk2 = vals[ii].value
								item2[mkk2] = $(vals[ii]).attr('label');
							}
						}
						if(item2len){
							item[key2] = item2;
							isv=true;
						}
					}
				}
			}
			if(isv){
				datas[tab.text()] = item;
				isv=false;
			}
		}
		
		countryData.set(datas);
	};
	var submitTabsForm = function(e){
		e.preventDefault(); 
		setCountryData(scope);
		refreshCountryList(scope);
		scopeDialog.dialog('close');
	};
	var getUiTab = function(scope){
		var i=0, index;
		$(".tabs.ui-tabs-nav li", scope).each(function(e){
			if($(this).hasClass('ui-tabs-selected')){
				index = i;
			}
			i++;
		});
		return $('.ui-tabs-panel', scope).eq(index);
	};
	
	$('.cms-countrylist-item').bind('click', function(e){
		scope = $(this);
		scopeDialog = $( '#'+$(this).attr('dialog') );
		var t = $(e.target);
		if(!t.hasClass('ui-icon-close')){return true;}
			var mmm = t.parents('.b'), index;
			if(t.parent().text() == 'ALL'){
				var uitab = getUiTab( scopeDialog );
				$("p input", uitab).each(function(){
					this.checked = false;
				});
				t.parents('.a').remove();
			}else{
				var dps = $('em', t.parents('.d')), bps = $('em', t.parents('.b')), bcs = $('.c', t.parents('.b')), pins=t.parent().prev('ins'),nins=t.parent().next('ins');
				if(dps.length > 1){
					t.parent().remove();
					if(nins.length==0){pins.remove();}else{nins.remove();}
				}else if(dps.length == 1 && bcs.length > 1){
					t.parents('.c').remove();
				}else if(bcs.length == 1){
					t.parents('.a').remove();
				}else if(bps.length >1){
					t.parent().remove();
					if(nins.length==0){pins.remove();}else{nins.remove();}
				}else if(bps.length == 1){
					t.parents('.a').remove();
				}else{
					return true;
				}
				var matches = t.parent().text().match(/\([A-Z]+\)/g);
				var mname = matches[0].replace('(', '').replace(')', '');
				$("p input[name="+mname+"]", scopeDialog).each(function(){
					this.checked = false;
				});
			}
		setCountryDataByDel(scope);
	});
	$('.cms-countrylist .reset-btn').bind('click', function(e){
		scope = $(this).parents('.cms-countrylist-item');
		scopeDialog=$('#'+scope.attr('dialog'))
		$('.list', scope).html('');
		countryData.init(scope);
		countryData.set('');
		$("p input", scopeDialog).each(function(){
			this.checked = false;
		});
	});
	$('.cms-countrylist .select-btn').bind('click', function(e){
		scope = $(this).parents('.cms-countrylist-item');
		if(!scope.attr('dialog')){
			var genid1 = TVB.util.genId(),genid2 = TVB.util.genId();
			scopeDialog = $('.cms-countrylist-pop', scope).dialog({
				bgiframe: true,
				resizable: false,
				width: 800,
				position: 'top',
				autoOpen: false,
				modal: true,
				autoSize: true,
				title: 'Select Region/Country',
				buttons: {
					'Submit':function(e){
						submitTabsForm(e);
					},
				},
				'open': function (event,ui){
                    $("button.ui-button",$(this).parent()).removeClass("ui-button").addClass("cms-btn")
                }
			}).attr('id', genid2).attr('link', genid1);
			scope.attr('id', genid1).attr('dialog', genid2);
			initCountryTabs();
			initCountrySubTabs();
		}// init dialog end
		scopeDialog=$('#'+scope.attr('dialog'))
		scopeDialog.dialog('open');
		scopeDialog.tabs('option','selected', parseInt( $('.tabs', scopeDialog).attr('selectIndex'), 10 ) );
	});// click region/country btn end
	
};

TVB.Cms.uiInit = function (scope) { 

    var com = TVB.Cms.Components;

    TVB.util.once(com.header, scope);
    com.laughing(scope);
    com.datepicker(scope);
    com.textarea(scope);
    com.time(scope);
    com.button(scope);
	com.countryList(scope);

};
